<?php
class OAuthAction extends TopAction {
	function authorize() {
		define ( 'TAO_OAUTH_REDIRECT_URL', TAO_APP_INDEX . '?s=OAuth/oauthlogin' );
		define ( 'TAO_OAUTH_ACCESS_URL', TAO_OAUTH_AUTHORIZE_URL . 'response_type=code&client_id=' . TAO_APPKEY . '&redirect_uri=' . TAO_OAUTH_REDIRECT_URL );
		echo '<a href="' . TAO_OAUTH_ACCESS_URL . '">获取授权码</a>';
// 		echo TAO_OAUTH_LOGIN_URL;
		
// 		$defs = get_defined_constants ( true );
// 		print_r ( $defs ['user'] );
	}
	function oauthlogin() {
		$code = $_REQUEST ['code']; // 通过访问https://oauth.taobao.com/authorize获取code
		$grant_type = 'authorization_code';
		$redirect_uri = TAO_APP_INDEX . '?s=OAuth/oauthlogin'; // 此处回调url要和后台设置的回调url相同
		$client_id = TAO_APPKEY; // 自己的APPKEY
		$client_secret = TAO_APPSECRET; // 自己的appsecret
		                                
		// 请求参数
		$postfields = array (
				'grant_type' => $grant_type,
				'client_id' => $client_id,
				'client_secret' => $client_secret,
				'code' => $code,
				'redirect_uri' => $redirect_uri 
		);
		
		$url = TAO_OAUTH_TOKEN_URL;
		
		$token = json_decode ( curl_post ( $url, $postfields ) );
		$access_token = $token->access_token;
		//echo json_encode ( $token );
		 
		$data['access_token'] = $access_token ;
		$vo = D('Seller')->where( "nick='{$_SESSION['seller_nick']}'")->save( $data ); 
		if( $vo ) {
			$this->success( '授权码已获取' , U('/Index') );
		} else {
			$this->error( '授权错误'.D('Seller')->getError(), U('/OAuth/authorize') );
		}
		
		
	}
}